import React, { useRef, useMemo } from "react"
import * as THREE from "three"
import { useFrame } from "@react-three/fiber"
import { shaderMaterial } from "@react-three/drei"
import { extend } from "@react-three/fiber"

// 防止process未定义错误
if (typeof window !== "undefined" && typeof window.process === "undefined") {
  window.process = { env: { NODE_ENV: "production" } }
}

// 自定义拖尾材质（带发光渐隐）- 直接使用字符串代替glsl宏
const TrailMaterial = shaderMaterial(
  {
    uTime: 0,
    uColor: new THREE.Color("#00ffff"),
  },
  // vertex shader
  `
    precision mediump float;
    uniform float uTime;
    attribute float aAlpha;
    varying float vAlpha;
    void main() {
      vAlpha = aAlpha;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  // fragment shader
  `
    precision mediump float;
    uniform float uTime;
    uniform vec3 uColor;
    varying float vAlpha;
    void main() {
      float glow = smoothstep(0.0, 1.0, vAlpha);
      gl_FragColor = vec4(uColor, vAlpha * glow);
    }
  `
)

// 扩展THREE以使用自定义材质
extend({ TrailMaterial })

function GlowingTrail({ positionBuffer }) {
  const meshRef = useRef()

  const geometry = useMemo(() => {
    // 防止首次渲染时空数组导致错误
    if (!positionBuffer || positionBuffer.length === 0) {
      return new THREE.BufferGeometry();
    }

    const geo = new THREE.BufferGeometry()
    geo.setAttribute(
      "position",
      new THREE.BufferAttribute(new Float32Array(positionBuffer.flat()), 3)
    )
    const alpha = new Float32Array(positionBuffer.length).map((_, i) => i / positionBuffer.length)
    geo.setAttribute("aAlpha", new THREE.BufferAttribute(alpha, 1))
    return geo
  }, [positionBuffer])

  useFrame(({ clock }) => {
    if (meshRef.current && meshRef.current.material) {
      meshRef.current.material.uTime = clock.getElapsedTime()
    }
  })

  return (
    <mesh ref={meshRef} geometry={geometry}>
      <trailMaterial transparent depthWrite={false} blending={THREE.AdditiveBlending} />
    </mesh>
  )
}

export { GlowingTrail }
